package com.trw.trp;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.utuan.log.Log;
import com.utuan.log.LogFactory;

public class AppConfiguration {

	private static Log log = LogFactory.getLog(AppConfiguration.class);
	private static AppConfiguration appConfiguration = new AppConfiguration();
	private static final String CONF_FILE = "/trp.properties";

	private boolean isMock;
	private ExecutorService threadPool;
	private Properties props = new Properties();

	private AppConfiguration() {
		Properties prop = loadProp(CONF_FILE);
		if (prop != null) {
			props.putAll(prop);
		}
		String externalFiles = props.getProperty("external.files");
		if (externalFiles != null) {
			String[] externalFileArray = externalFiles.split(",");
			if (externalFileArray != null && externalFileArray.length > 0) {
				for (String externalFile : externalFileArray) {
					prop = loadProp(externalFile);
					if (prop != null) {
						props.putAll(prop);
					}
				}
			}
		}
		log.debug("loaded properties:" + props);
		this.isMock = Boolean.parseBoolean((String) props.get("ismock"));
		int threadCount = 1;
		try {
			threadCount = Integer.parseInt((String) props.get("thread.count"));
		} catch (NumberFormatException nfe) {
			log.warn(nfe);
		}
		threadPool = Executors.newFixedThreadPool(threadCount);
	}

	private Properties loadProp(String file) {
		Properties prop = null;
		InputStream is = AppConfiguration.class.getResourceAsStream(file);

		if (is == null) {
			is = ClassLoader.getSystemResourceAsStream(file);
		}
		if (is == null) {
			log.debug("configure file not exist:" + file);
		} else {
			prop = new Properties();
			try {
				prop.load(is);
			} catch (IOException e) {
				log.warn(e);
			}
		}
		return prop;
	}

	public static AppConfiguration getInstance() {
		return appConfiguration;
	}

	public boolean isMock() {
		return isMock;
	}

	public ExecutorService getThreadPool() {
		return threadPool;
	}

	public String getProperty(String key) {
		String ret = null;
		if (props != null) {
			ret = (String) props.get(key);
		}
		return ret;
	}

}
